﻿/**************************************************************
 * Copyright Eastmoney Corporation. All rights reserved.
 * 
 * Author: guitao(guitao@eastmoney.com) 
 * Create Date: 2020/10/26 15:02:21
 * Description:
 *          
 * Revision History:
 *      Date         Author               Description
 *              
***************************************************************/

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace QuartzJob.Sample
{
    /// <summary>
    /// 需要dispose
    /// 1.IDisposableService可以注册为Singleton,会自动dispose
    /// 2.如果不能注册单例，则如本例方式通过IServiceProvider.CreateScope方式处理
    /// </summary>
    [DisallowConcurrentExecution]
    public class DisposedSampleJob : IJob
    {
        private readonly ILogger<DisposedSampleJob> _logger;
        private readonly IServiceProvider _serviceProvider;

        public DisposedSampleJob(ILogger<DisposedSampleJob> logger,
            IServiceProvider serviceProvider)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            //if IDisposableService register Transient,use CreateScope to dispose IDisposableService 
            //if IDisposableService register singleton,it can be inject directly and dispose automatically
            using (var scope = _serviceProvider.CreateScope())
            {
                var service = scope.ServiceProvider.GetRequiredService<IDisposableService>();
                _logger.LogInformation($"{nameof(DisposedSampleJob)} executed at {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}.");
                await Task.CompletedTask;
            }
        }
    }
}
